#ifndef MOTOR_DRIVE_H
#define MOTOR_DRIVE_H

class MOTOR_DRIVER{
    public:
        MOTOR_DRIVER(uint8_t, uint8_t, uint8_t); //PA, PB, Channel
        void run(int16_t);
        // void updateDistance(float, bool);
        double  now_speed;
        int64_t nowDistance=0;
    private: 
        uint8_t Channel;
        uint8_t Pin_A;
        uint8_t Pin_B;
        uint8_t now_attach_pin=255;
};       

MOTOR_DRIVER :: MOTOR_DRIVER(uint8_t PA, uint8_t PB, uint8_t motorChannel){
    // 初始化一个电机，提供其关联管脚与电机号
    this->Channel = motorChannel;
    this->Pin_A = PA;
    this->Pin_B = PB;
    this->now_attach_pin = PA;
    // ledcSetup(this->motorChannel, 0, 10);
    ledcSetup(this->Channel, 3000, 10);
    // ledcWriteTone(this->Channel, 3000);
    ledcWrite(this->Channel, 0);
    ledcAttachPin(this->Pin_A, this->Channel);
    pinMode(this->Pin_B, OUTPUT);
    digitalWrite(this->Pin_B, LOW);
}

void MOTOR_DRIVER :: run(int16_t speed){
    // 初始化一个电机，提供其关联管脚与电机号
    if(speed > 0){
        if (this->now_attach_pin != this->Pin_A){
            ledcDetachPin(this->Pin_B);
            ledcAttachPin(this->Pin_A, this->Channel);
            this->now_attach_pin = this->Pin_A;
        }
    }else if (speed < 0){
        if (this->now_attach_pin != this->Pin_B){
            ledcDetachPin(this->Pin_A);
            ledcAttachPin(this->Pin_B, this->Channel);
            this->now_attach_pin = this->Pin_B;
        }
        speed = -speed;
    }
    // ledcWriteTone(this->Channel, 3000);
    ledcWrite(this->Channel, speed);
}

class LED_DRIVER{
    public:
        LED_DRIVER(uint8_t, uint8_t);
        void set(uint8_t);
        void taskBlink(void * );
        void taskFade(void * );
        double  now_speed;
        uint8_t now_fade;
        uint16_t blinkInterval=500;
        uint8_t  now_duty;
    private: 
        uint8_t Channel;
        uint8_t now_attach_pin;
}; 

LED_DRIVER :: LED_DRIVER(uint8_t pinNum, uint8_t Channel){
    this->Channel = Channel;
    this->now_attach_pin = pinNum;
    ledcSetup(this->Channel, 1, 10);
    ledcWrite(this->Channel, 0);
    ledcWriteTone(this->Channel, 3000);
    ledcAttachPin(this->now_attach_pin, this->Channel);
}

void LED_DRIVER :: set(uint8_t duty){
    ledcWrite(this->Channel, duty);
    this->now_duty = duty;
}

void LED_DRIVER :: taskFade(void * ptr){
    while(true){
        /* code */
    } 
}

void LED_DRIVER :: taskBlink(void * ptr){
    while(true){
       ledcWrite(this->Channel, 0);
       vTaskDelay(blinkInterval);
       ledcWrite(this->Channel, this->now_duty);
       vTaskDelay(blinkInterval);
    } 
}

#endif